#!/usr/bin/env python

import RPi.GPIO as GPIO
from time import sleep
import select
import datetime
import array
import struct
import time
import os
touchOut = 24
touchPin = 12
count = 0
temptime = ''

#remove '0x' and convert to int
def addZero(s):
	s = s[2:]
	length = len(s)
	while length<4:
		s = '0'+s
		length = length + 1
	return s 

def convertToBit(s):
	#print(s)
	temp = s[2:]
	#print(temp)
	#print type(temp)
	first = bin(int(temp[0],16))
	second = bin(int(temp[1],16))
	first = addZero(first)
	second = addZero(second)
	
	return first + second

def xor(check,bin8):
	i = 0
	res = ''
	while i<8:
		if check[i] == bin8[i]:
			#print 'same'
			res = res + '1'
		else:
			res = res + '0'
		i = i + 1
	#print 'res' + res
	return res


#checkValue
def checkValue(s):
	h = array.array('b',s)
	check = convertToBit(hex(h[0]))
	
	for i in range(1,len(h)):
		
		bin8 = convertToBit(hex(h[i]))
		#print bin8
		check = xor(check,bin8)
		#print 'che'+check
		
	#print hex(int(check,2))[2:]
	return hex(int(check,2))[2:]


#get time


def getTotalTime():
	now = time.time()
	s = int(now)
	ms = int(round(now * 1000)) % 1000
	return str(s) + '.' + str(ms)

def getUTC():
	fd = os.open("myfifo",os.O_RDONLY)
	inputs = [fd]
	outputs = []
	readable,writeable,exceptional = select.select(inputs,outputs,inputs)
	rf = readable[0]
	s = os.read(fd,9)
	print(s)
	print(readable)
	os.close(fd)
	sleep(0.5)
	return s

def saveRisingTime():
    str_ts = getTotalTime()
    str_ts = "p"+str_ts
    print(str_ts)
    fp=open("pps_rise_time.txt",mode='a+')
    fp.write(str_ts)
    fp.close()
#save package
def savePackage(data,filename):
	length = len(data)
	fp = open(filename,mode='ab+')
	header = struct.pack('B',0x7b)
	kind = struct.pack('B',0x04)
	length_07 = struct.pack('B',0x25)
	length_815 = struct.pack('B',0x00)	
	length_1623 = struct.pack('B',0x00)
	length_2431 = struct.pack('B',0x00)
	i = 1
	ppsdata = struct.pack('c',data[0])
	while i<length:
		ppsdata = ppsdata + struct.pack('c',data[i])
		i = i + 1
	rail1 = struct.pack('B',0x0d)
	rail2 = struct.pack('B',0x0a)
	print kind
	print header
	
	fp.write(header)
	fp.write(kind)
	fp.write(length_07)
	fp.write(length_815)
	fp.write(length_1623)
	fp.write(length_2431)
	fp.write(data)
	fp.write(rail1)
	fp.write(rail2)
	
	fp.close()
	print('dayinok----')


	
def getFileName():
	while 1:
		try:
			fp = open("filenameTemp.txt","rb+")
			filename = fp.readline()
			fp.close()
			print(filename)
			return filename[:-1]
		except IOError as e:
			print('error:')
			sleep(0.002)	
	
if __name__ == "__main__":
	
	#get filename
	filename = getFileName();
	path = "/media/ubuntu/bae/"+filename+"/pps"
 		
	
	GPIO.setmode(GPIO.BCM)
	'''
	GPIO.setup(touchOut,GPIO.OUT)
	while 1:
		GPIO.output(touchOut,0)
		sleep(1)
		GPIO.output(touchOut,1)
		sleep(1)
	
	'''
	GPIO.setup(touchPin,GPIO.IN)
	
	first = getUTC()


	while 1:
		GPIO.wait_for_edge(touchPin,GPIO.RISING)
		print 'low to high'

		
		saveRisingTime()			
		temp = getTotalTime()
 
		data = '$' + first + ',' + temp
		ch = checkValue(data[1:])
		data = data + "*" + ch
		print data
		savePackage(data,path)
		first = getUTC()
	
	GPIO.cleanup()
	
